// 渲染器管理模块
class DevToolsRenderer {
    constructor() {
        this.renderers = {};
        this.initialized = false;
        this.currentTool = null;
        this.activeIntervals = [];
        this.activeTimeouts = [];
    }

    initRenderers() {
        // 动态注册所有工具渲染器，带安全检查
        this.registerRenderer('json-formatter', window.JSONFormatterRenderer);
        this.registerRenderer('sql-generator', window.SQLGeneratorRenderer);
        this.registerRenderer('base64-encoder', window.Base64EncoderRenderer);
        this.registerRenderer('timestamp-converter', window.TimestampConverterRenderer);
        this.registerRenderer('url-encoder', window.URLEncoderRenderer);
        this.registerRenderer('hash-generator', window.HashGeneratorRenderer);
        this.registerRenderer('jwt-parser', window.JWTParserRenderer);
        this.registerRenderer('sql-formatter', window.SQLFormatterRenderer);
        this.registerRenderer('text-deduplicator', window.TextDeduplicatorRenderer);
        this.registerRenderer('uuid-generator', window.UUIDGeneratorRenderer);
        this.registerRenderer('password-generator', window.PasswordGeneratorRenderer);
        this.registerRenderer('text-diff', window.TextDiffRenderer);
        this.registerRenderer('rmb-converter', window.RMBConverterRenderer);
        this.registerRenderer('qr-code', window.QRCodeRenderer);
        this.registerRenderer('http-status', window.HttpStatusRenderer);
        this.registerRenderer('regex-tester', window.RegexTesterRenderer);
        this.registerRenderer('color-toolkit', window.ColorToolkitRenderer);
        this.registerRenderer('css-formatter', window.CSSFormatterRenderer);
        this.registerRenderer('markdown-preview', window.MarkdownPreviewRenderer);
        this.registerRenderer('code-formatter', window.CodeFormatterRenderer);
        this.registerRenderer('api-tester', window.APITesterRenderer);
        this.registerRenderer('xml-formatter', window.XMLFormatterRenderer);
        
        // 渲染器初始化完成
    }

    registerRenderer(toolId, rendererClass) {
        if (rendererClass && typeof rendererClass.getHTML === 'function' && typeof rendererClass.init === 'function') {
            this.renderers[toolId] = rendererClass;
        }
    }

    renderTool(toolId) {
        // 清理上一个工具的资源
        this.cleanup();
        
        // 确保渲染器已初始化
        if (!this.initialized) {
            this.initRenderers();
            this.initialized = true;
        }
        
        const contentArea = document.getElementById('main-content');
        if (!contentArea) {
            return;
        }
        
        // 记录当前工具
        this.currentTool = toolId;

        const renderer = this.renderers[toolId];
        if (!renderer) {
            contentArea.innerHTML = `
                <div class="flex items-center justify-center h-64">
                    <div class="text-center">
                        <i data-feather="alert-circle" class="w-16 h-16 text-gray-400 mx-auto mb-4"></i>
                        <p class="text-gray-500">工具 "${toolId}" 未找到</p>
                    </div>
                </div>
            `;
            this.initFeatherIcons();
            return;
        }

        try {
            // 渲染工具HTML
            const html = renderer.getHTML();
            contentArea.innerHTML = html;

            // 初始化工具
            renderer.init();

            // 初始化图标
            this.initFeatherIcons();
        } catch (error) {
            console.error(`渲染工具 ${toolId} 时出错:`, error);
            contentArea.innerHTML = `
                <div class="flex items-center justify-center h-64">
                    <div class="text-center">
                        <i data-feather="alert-circle" class="w-16 h-16 text-red-400 mx-auto mb-4"></i>
                        <p class="text-red-500">渲染工具时出错: ${error.message}</p>
                    </div>
                </div>
            `;
            this.initFeatherIcons();
        }
    }

    cleanup() {
        // 清理所有活动的定时器
        this.activeIntervals.forEach(intervalId => {
            clearInterval(intervalId);
        });
        this.activeIntervals = [];
        
        this.activeTimeouts.forEach(timeoutId => {
            clearTimeout(timeoutId);
        });
        this.activeTimeouts = [];
        
        // 清理全局定时器（向后兼容）
        if (window.devToolsIntervals) {
            window.devToolsIntervals.forEach(intervalId => {
                clearInterval(intervalId);
            });
            window.devToolsIntervals = [];
        }
        
        if (window.devToolsTimeouts) {
            window.devToolsTimeouts.forEach(timeoutId => {
                clearTimeout(timeoutId);
            });
            window.devToolsTimeouts = [];
        }
        
        // 调用当前工具的清理方法（如果存在）
        if (this.currentTool && this.renderers[this.currentTool] && 
            typeof this.renderers[this.currentTool].cleanup === 'function') {
            try {
                this.renderers[this.currentTool].cleanup();
            } catch (error) {
                console.warn(`清理工具 ${this.currentTool} 时出错:`, error);
            }
        }
    }
    
    // 提供给渲染器注册定时器的方法
    registerInterval(callback, delay) {
        const intervalId = setInterval(callback, delay);
        this.activeIntervals.push(intervalId);
        return intervalId;
    }
    
    registerTimeout(callback, delay) {
        const timeoutId = setTimeout(callback, delay);
        this.activeTimeouts.push(timeoutId);
        return timeoutId;
    }

    initFeatherIcons() {
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 100);
    }
}